package com.danan.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.danan.realtime.app.BaseApp;
import com.danan.realtime.common.Constant;
import com.danan.realtime.pojo.UserLoginBean;
import com.danan.realtime.util.SinkUtil;
import com.danan.realtime.util.TimeUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import scala.collection.immutable.Stream;

import java.time.Duration;

/**
 * @author NanHuang
 * @Date 2023/1/26
 */
public class DwsApp_4_user_user_login_window extends BaseApp {
    public static void main(String[] args) {
        new DwsApp_4_user_user_login_window().init(
                5004,
                3,
                "DwsApp_4_user_user_login_window",
                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    @Override
    public void invoke(StreamExecutionEnvironment env, DataStreamSource<String> ds) {
        // 1 过滤数据，封装POJO
        SingleOutputStreamOperator<UserLoginBean> beanDs = toUserLoginBean(ds);
        // 2 开窗聚合
        SingleOutputStreamOperator<UserLoginBean> resultDs = windowAndAgg(beanDs);
        // 3 将结果写入到Clickhouse中
        resultDs.addSink(SinkUtil.getClickhouseSink(Constant.TOPIC_DWS_USER_USER_LOGIN_WINDOW,UserLoginBean.class));
    }

    private SingleOutputStreamOperator<UserLoginBean> windowAndAgg(SingleOutputStreamOperator<UserLoginBean> ds) {
        // 1 创建水印策略
        WatermarkStrategy<UserLoginBean> strategy = WatermarkStrategy.<UserLoginBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((s, l) -> s.getTs())
                .withIdleness(Duration.ofSeconds(60));
        // 2 开窗聚合
        return ds.assignTimestampsAndWatermarks(strategy)
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<UserLoginBean>() {
                    @Override
                    public UserLoginBean reduce(UserLoginBean t1, UserLoginBean t2) throws Exception {
                        t2.setBackCt(t2.getBackCt() + t1.getBackCt());
                        t2.setUuCt(t2.getUuCt() + t1.getUuCt());
                        return t2;
                    }
                }, new AllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<UserLoginBean> values, Collector<UserLoginBean> out) throws Exception {
                        UserLoginBean result = values.iterator().next();
                        result.setStt(TimeUtil.parseDateStr(window.getStart(),true));
                        result.setEdt(TimeUtil.parseDateStr(window.getEnd(),true));
                        result.setTs(System.currentTimeMillis());
                        out.collect(result);
                    }
                });
    }

    private SingleOutputStreamOperator<UserLoginBean> toUserLoginBean(DataStreamSource<String> ds) {
        return ds.map(JSON::parseObject)
                .filter(j -> (j.getString("last_page_id") == null || "login".equals(j.getString("last_page_id"))) && j.getString("uid") != null)
                .keyBy(j -> j.getString("mid"))
                .process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {


                    private MapState<String, Object> flagData;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        flagData = getRuntimeContext().getMapState(new MapStateDescriptor<String, Object>("flagData", String.class, Object.class));
                    }

                    @Override
                    public void processElement(JSONObject value, KeyedProcessFunction<String, JSONObject, UserLoginBean>.Context ctx, Collector<UserLoginBean> out) throws Exception {
                        Long ts = value.getLong("ts");
                        String currentDate = TimeUtil.parseDateStr(ts, false);
                        long flagTs = (long)(flagData.get("ts") == null ? Long.MAX_VALUE : flagData.get("ts"));
                        String flagDate = (String) (flagData.get("date") == null ? "9999-99-99" : flagData.get("date"));
                        long uuCt = 0L;
                        long backCt = 0L;
                        if (!currentDate.equals(flagDate)){
                            uuCt = 1L;
                            flagData.put("ts",ts);
                            flagData.put("date",currentDate);
                            if (ts - flagTs > 7 * 24 * 60 * 60 * 1000){
                                backCt = 1L;
                            }
                        }
                        if (uuCt == 1){
                            out.collect(
                                    UserLoginBean.builder()
                                            .backCt(backCt)
                                            .uuCt(uuCt)
                                            .ts(ts)
                                            .build()
                            );
                        }
                    }
                });
    }
}
